package com.ajie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ajie.config.annotation.RestControllerMapping;
import com.ajie.entity.SysUser;
import com.ajie.entity.dto.Option;
import com.ajie.model.PageParams;
import com.ajie.model.Result;
import com.ajie.service.SysUserService;
import com.ajie.utils.PasswordUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * @author: ajie
 * @createTime: 2024-06-22 18:11
 */
@Tag(name = "用户管理")
@RestControllerMapping("user")
@ApiSupport(author = "ajie:xxxx@qq.com", order = 1)
public class SysUserController {

    @Resource
    private SysUserService userService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @GetMapping("info/{id}")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "通过ID查询单条数据", parameters = {
            @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
    })
    public Result<SysUser> getById(@PathVariable String id){
        return Result.success(userService.getById(id));
    }

    /**
     * 分页查询
     * @return 查询结果
     */
    @PostMapping("page")
    @Operation(summary = "分页查询")
    @ApiOperationSupport(order = 2)
    public Result<Page<SysUser>> pageQuery(@RequestBody PageParams<SysUser> pageParams){
        SysUser params = pageParams.getParams();
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.like(StrUtil.isNotBlank(params.getNickname()), SysUser::getNickname, params.getNickname());
        Page<SysUser> page = userService.page(pageParams.getPage(), lqw);
        page.getRecords().forEach(item -> item.setRoles(userService.getRoles(item.getId())));
        return Result.success(page);
    }

    /**
     * 分页查询
     * @return 查询结果
     */
    @PostMapping("list")
    @Operation(summary = "列表查询")
    @ApiOperationSupport(order = 2)
    public Result<List<SysUser>> pageQuery(@RequestBody SysUser user){
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.like(StrUtil.isNotBlank(user.getNickname()), SysUser::getNickname, user.getNickname());
        lqw.eq(user.getSex() != null, SysUser::getSex, user.getSex());
        return Result.success(userService.list(lqw));
    }

    /**
     * 新增数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @PostMapping("insert")
    @Operation(summary = "新增数据")
    @ApiOperationSupport(order = 3)
    public Result<Boolean> insert(@RequestBody SysUser sysUser){
        String slat = RandomUtil.randomString(16);
        sysUser.setSlat(slat);
        String password = sysUser.getPassword();
        String encrypt = PasswordUtils.encrypt(slat, password);
        sysUser.setPassword(encrypt);
        if (userService.save(sysUser)) {
            List<Option> roles = sysUser.getRoles();
            if (roles.size() > 0) {
                List<Object> roleIds = roles.stream().map(Option::getValue).toList();
                userService.insertRole(sysUser.getId(), roleIds);
            }
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 更新数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @PostMapping("update")
    @Operation(summary = "更新数据")
    @ApiOperationSupport(order = 4)
    public Result<SysUser> update(@RequestBody SysUser sysUser){
        if (sysUser.getRoles() != null) {
            userService.deleteRole(sysUser.getId());
        }
        String slat = RandomUtil.randomString(16);
        sysUser.setSlat(slat);
        String password = sysUser.getPassword();
        String encrypt = PasswordUtils.encrypt(slat, password);
        sysUser.setPassword(encrypt);
        if (userService.updateById(sysUser)) {
            if (sysUser.getRoles() != null) {
                List<Option> roles = sysUser.getRoles();
                if (roles.size() > 0) {
                    List<Object> roleIds = roles.stream().map(Option::getValue).toList();
                    userService.insertRole(sysUser.getId(), roleIds);
                }
            }
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @GetMapping("/delete/{id}")
    @Operation(summary = "通过主键删除数据", parameters = {
            @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
    })
    @ApiOperationSupport(order = 5)
    public Result<Boolean> deleteById(@PathVariable String id){
        if (userService.removeById(id)) {
            return Result.success();
        }
        return Result.error();
    }

}
